<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" >
				<el-form-item>
					<el-input v-model="keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryKeyword">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>

			<el-table-column prop="name" label="名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="dirPath" label="路径" width="100" :formatter="formatSex" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" sortable>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员id" width="120" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" min-width="180" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="totals" :current-page="currentPage"  style="float:right;">
			</el-pagination>
		</el-col>




    <!-- 添加或修改的对话框
    el-dialog - elementUi提供的对话框 = 模态框
    	:title="title" - 动态改变标题
    	:visible.sync="saveFormVisible"  - 模态框的显示状态
    	:close-on-click-modal="false" - 关闭模态框只能通过模态框的x关闭，点击空白处不能关闭模态框
    el-form - 表单
    	:model="saveForm" - 绑定表单对象
    	label-width="80px" - 标签宽度
    	:rules="saveFormRules" - 验证规则
    	ref="saveForm" - 为当前模态框取名
    	prop="name" - 如果当前字段要验证，就必须写，出现*
    	auto-complete="off" - 不自动提示
-->
		<!--编辑界面-->
		<el-dialog :title="title"  :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>

				<el-form-item label="state">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>

        <el-form-item label="部门经理" >
          <!--
              el-select - 下拉框
                v-model="saveForm.manager_id" - 回显数据
                placeholder="请选择" - 提示语
                clearable - 可清理
                el-option - 每一个选项
                v-for="item in managers" - 遍历
                :label="item.username" - 回显哪一个值：item对象的username属性
                :value="item" - 点击保存你要传递到后端的数据
              回显机制：
                v-model="saveForm.manager"  与 v-for中的对应
                :label="item.username" - 回显哪一个值：item对象的username属性
                value-key	作为 value 唯一标识的键名，绑定值为对象类型时必填
                value-key="id" - 因为我们绑定的是一个对象saveForm.manager，
                  对象里面有多个值： id: 324, username: "东邪"
                使用id作为回显的唯一标识
            -->
          <el-select v-model="saveForm.manager_id" placeholder="请选择">
            <el-option v-for="item in managers"
                       :label="item.username"
                       :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}
		</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" >
          <!--
             el-cascader - 级联
               :options="deptTree" - 级联框中需要的数据【集合】
             回显机制：
               v-model="saveForm.parent"
               parent：[2,5]
           -->
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
            	checkStrictly: true,
                label: 'name', // 级联框显示那个属性的值
                value: 'id'    // 回显时需要,回传值的时候也需要
            }" clearable>
          </el-cascader>
        </el-form-item>


			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>


	</section>
</template>

<script>

	export default {
		data() {
			return {
       //分页相关的数据
        departments: [],//绑定到表格，显示列表数据
        totals: 0,      //总条数
        currentPage:2,  //当前页
        pageSize: 5,    //当前页显示的数据


        //高级查询参数
        keyword:'',

        //批量删除参数
				sels: [],//列表选中列

				saveFormVisible: false,//编辑界面是否显示
				saveLoading: false,     //加载框
				title :'',              //标题
        saveFormRules: { //严重规则
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
          sn: [
            { required: true, message: '请输入部门编号', trigger: 'blur' }
          ]
				},
				//编辑界面数据
				saveForm: {
					id: null,
					sn: null,
          name: '',
					state: 1,
					manager_id: null,
					parent_id: null,
          parent: null
				},
        //部门经理
        managers:[],

        //部门树
        deptTree:[]

			}
		},
		methods: {
      //获取用户列表
     //1*分页栏方法
      getDepartments() {
        let para = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keyword:this.keyword

        };
        this.listLoading = true;
        //NProgress.start();
        this.$http.post("/department",para).then((res) => {
          this.totals = res.data.totals;
          this.departments = res.data.data;
          this.listLoading = false;
          //NProgress.done();
        }).catch(res =>{
          this.$message.error('系统繁忙');
        });
      },
     //2*分页查询方法
      handleCurrentChange(val) {
        this.currentPage = val; //var前端的当前页
        this.getDepartments();
      },
    //3*高级查询方法
      queryKeyword() {
      this.currentPage = 1; //var前端的当前页
      this.getDepartments();
    },


			//4*删除方法
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {//点击了确认
					this.listLoading = true;//页面加载忙等
          this.$http.delete("/department/"+row.id).then(result =>{
            result = result.data;
            if (result.success){
              this.$message({
                message: result.message,
                type: 'success'
              });
              //如果时最后一页并且时最后一条数据的时候：当前页 = 当前页-1
              //最后一条数据：(this.totals - 1)%this.pageSize == 0
              //总页数：Math.ceil(this.totals/this.pageSize)
              var totalPage = Math.ceil(this.totals/this.pageSize);
              if(totalPage==this.currentPage && this.currentPage>1 && (this.totals - 1)%this.pageSize == 0){
                this.currentPage = this.currentPage - 1;
              }
              //刷新
              this.getDepartments()
            }else {
              this.$message({
                message: "系统繁忙稍后重试",
                type: 'error'
              });
              //业务删除后是否需要定位到第一页
              this.currentPage = 1;
              //刷新
              this.getDepartments()
            }
          }).catch(result=>{
            this.listLoading = false;//页面加载忙等
            this.$message({
              message: "系统繁忙稍后重试",
              type: 'error'
            });
          })
          //   removeDepartment(para).then((res) =>{
          //       this.listLoading = false;
					// 	this.$message({
					// 		message: '删除成功',
					// 		type: 'success'
					// 	});
					// 	this.getDepartments();
					// });
				}).catch(() => {//点击取消按钮

				});
			},

      //5*选项改变的时候触发
      selsChange: function (sels) {
        this.sels = sels;
      },






      //6*批量删除
      batchRemove: function () {
       //获取被选中的对象id们
        var ids = this.sels.map(item => item.id)
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;//加载忙等框
          this.$http.patch("/department",ids).then(res=>{
          this.listLoading = false
          if (res.data.success){
              this.currentPage = 1;//返回第一页
            this.getDepartments()  //刷新
          }else {
            this.$message.error("批量删除失败【500】");
          }

          }).catch( res =>{
            this.$message.error("系统错误【400,404】");

          });

        }).catch(() => {

        });
      },

      //7*点击修改按钮弹出对话框
			handleEdit: function (index, row) {

        this.title = "编 辑"
				this.saveForm = Object.assign({}, row);
        this.getManagers();
        this.getDeptTree();

        //对上级部门回显做处理
        let  dirPath = row.dirPath;//获取这个数组-- /2/5/10 - [2,5]
        let  dirArr = dirPath.split("/")     //去掉这个/
        var arr =[];
        //将里边的数据放到一个新数组里边
        for (var i = 1;i < dirArr.length-1;i++){
          arr[i-1] = parseInt(dirArr[i])  //parseInt  将字符串转换为普通格式
        }
        this.saveForm.parent = arr;

        this.saveFormVisible = true;
			},
			//8*点击添加按钮弹出对话框
			handleAdd: function () {
        this.title = "添 加"
				this.saveForm = {
          id: null,
          name: '',
          state: 1,
          manager_id: null,
          parent_id: null,
          manager: null,
          parent: null
				};
        this.getManagers();
        this.getDeptTree();
        this.saveFormVisible = true;
			},
			//9*点击模态框提交数据
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
							//NProgress.start();
							//获取修改需要传进去的对象
              let para = Object.assign({}, this.saveForm);


            //对提交数据时上级部门格式做出处理
             var parentTmp =  para.parent
            //加一个判断必须要有上级部门
              if (parentTmp){
                para.parent = null //后端是用对象接收，前端是[]这里格式不对，避免400
                para.parent_id =parentTmp[parentTmp.length-1];

              }




            this.$http.put("/department",para).then(res=>{
              //操作完毕关闭添加和修改模态框
              this.saveFormVisible = false
              this.saveLoading = false
              if (res.data.success){
                this.$message.success("操作成功");
                this.getDepartments();

              }else {
                this.$message.error("系统错误【500】");
              }

            }).catch(res=>{
            this.$message.error("系统错误【400,404】");

            })

						});
					}
				});
			},


      getManagers() {
        this.$http.get("/employee").then(res => {
          this.managers = res.data;//给部门经理赋值
        })
      },
      getDeptTree() {
        this.$http.get("/department/deptTree").then(res => {
          this.deptTree = res.data;//给部门树赋值
        })
      },

    },
		mounted() {
			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>